package nsu.edu.zsq.util;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.commons.collections.MapUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

import nsu.edu.zsq.exception.ParamException;

/** 
* Description: 实体类的数据检验<br>
*/
public class BeanValidator {
    
    /**
     * 全局的校验工厂
     */
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    
    @SuppressWarnings("unchecked")
    public static <T> Map<String, String> validate(T t, Class<T>... groups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<T>>  validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap<String, String> errors = new LinkedHashMap<>();
            Iterator<ConstraintViolation<T>> itertor = validateResult.iterator();
            while (itertor.hasNext()) {
                ConstraintViolation<T> violation = (ConstraintViolation<T>)itertor.next();
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }
    
    @SuppressWarnings("unchecked")
    public static Map<String, String> validateList(Collection<?> collection) {
        // 如果为空则直接抛出空指针异常
        Preconditions.checkNotNull(collection);
        Iterator<?> itertor = collection.iterator();
        Map<String, String> errors;
        do {
            if (!itertor.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = itertor.next();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());
        
        return errors;
    }
    
    /**
     * 传入单个对象，或者多个对象，检验对象中数据的合法性，返回不合法的字段+错误信息
     * @param first 单个对象
     * @param objects 多个对象
     * @return Map<String, String> key：字段，value：错误信息
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }
    
    /**
     * 对请求发送过来的数据对象进行检查，如果校验不通过就抛出异常
     * @param param 实体类
     * @throws ParamException 自定义的数据检验异常
     */
    public static void check(Object param) throws ParamException {
        Map<String, String> map = BeanValidator.validateObject(param);
        if (MapUtils.isNotEmpty(map)) {
            throw new ParamException(map.toString());
        }
    }
}
